﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Caching;

namespace Janus.Cores.Cacheing
{
    public static class CacheHelper
    {
        private static int _minutes;

        static CacheHelper()
        {
            string minutes = ConfigurationManager.AppSettings["CacheSlidingTime"];
            if (string.IsNullOrEmpty(minutes) || !int.TryParse(minutes, out _minutes))
            {
                _minutes = 10; // 默认为10分钟。
            }
        }

        /// <summary>
        /// 添加指定内容到缓存中。
        /// </summary>
        /// <param name="key">缓存键值。</param>
        /// <param name="value">缓存内容。</param>
        public static void SetCache(string key, object value)
        {
            SetCache(key, value, _minutes);
        }

        /// <summary>
        /// 添加指定内容到缓存中。
        /// </summary>
        /// <param name="key">缓存键值。</param>
        /// <param name="value">缓存内容。</param>
        public static void SetCache(string key, object value, int minutes)
        {
            Cache cache = HttpRuntime.Cache;
            if (value != null)
            {
                cache.Insert(key, value, null, System.DateTime.Now.AddMinutes(minutes), TimeSpan.Zero);
            }
        }

        /// <summary>
        /// 获取指定键值的缓存。
        /// </summary>
        /// <param name="key">缓存键值。</param>
        /// <returns></returns>
        public static object GetCache(string key)
        {
            Cache cache = HttpRuntime.Cache;
            return cache[key];
        }

        /// <summary>
        /// 清除指定键值的缓存。
        /// </summary>
        /// <param name="key">缓存键值。</param>
        public static void ClearCache(string key)
        {
            Cache cache = HttpRuntime.Cache;
            cache.Remove(key);
        }
    }
}
